﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CarlosAg.ExcelXmlWriter;

namespace Medianamik.Globalization.Utilities
{
    public static class ExcelResourceConverter
    {
        public static IEnumerable<Resource> ToResources(this Workbook wb)
        {
            var resources = new List<Resource>();
            foreach(Worksheet ws in wb.Worksheets)
            {
                for(int i = 2; i < ws.Table.Rows.Count;i++)
                {
                    var resource = ws.Table.Rows[i].ToResource(ws.Table.Rows[0].Cells[1].Data.Text);
                    if(resource != null)
                        resources.Add(resource);
                }
            }
            return resources;
        }
        public static Resource ToResource(this WorksheetRow row, string resourceSet)
        {
            if (row == null)
                throw new ArgumentNullException("row");

            if (String.IsNullOrEmpty(resourceSet))
                throw new ArgumentNullException("resourceSet");

            if (row.Cells.Count < 2)
                throw new ArgumentException("Cell count is smaller than 2, impossible to convert.");

            if (row.Cells.Count == 2)
                return null;

            if (row.Cells.Count == 3)
            {
                var valueText = row.Cells[2].Data.Text;
                if (String.IsNullOrEmpty(valueText) || valueText.Trim().Length == 0)
                    return null;
            }
            return new Resource(row.Cells[0].Data.Text, row.Cells[1].Data.Text, row.Cells[2].Data.Text, resourceSet);
        }
        
        public static WorksheetRow ToWorksheetRow(this Resource resource)
        {
            if (resource == null)
                throw new ArgumentNullException("resource");

            const DataType type = DataType.String;
            
            var excelRow = new WorksheetRow();

            excelRow.Cells.Add(new WorksheetCell(resource.Id, type));
            excelRow.Cells.Add(new WorksheetCell(resource.CultureName, type));
            excelRow.Cells.Add(new WorksheetCell(resource.Value, type));

            return excelRow;
        }
    }
}
